<?php
/* 用户表 */
namespace app\api\model;


use extra\Constant;
use think\Db;
use think\Model;
use app\api\model\MessageBox;

class MessageTargetUser extends Model {


    protected $tableName = 'message_target_user';
    
    const MESSAGE_STATUS_DRAFT=1;//存草稿箱
    const MESSAGE_STATUS_OK=2;//发布状态
    const MESSAGE_STATUS_DELETE=3;//删除
    
    /*
     * 通过用户ID获取对应的消息
     */
//    public function getMyMsgList($condition,$paginate=[],$orderBy=[]){
////        $result=[];
//        $list = \think\Db::name($this->tableName)->where($condition)->order($orderBy)->paginate($paginate)->each(function($item,$key){
////            dump($item); //这里可以打印出是个一维数组
//            $result=[];
//            $result['msg_id']=$item['m_b_id'];
//            $result['activity_id']= 0;
//            $result['msg_time_str']=date('Y-m-d H:i',$item['add_time']);
//
//
//            //获取消息内容
//            $messageBoxModel=new MessageBox;
//            $messageBoxData=$messageBoxModel->getOneMessageBoxDataByID($item['m_b_id']);
//
//            $result['msg_title']=$messageBoxData['title'];
//            $result['msg_description']=$messageBoxData['abstract'];
//            $result['msg_img_url']=$messageBoxData['cover_picture_link'];
//            if($messageBoxData['type']==MessageBox::ACTIVITY_TYPE){
//                $result['msg_url']=$messageBoxData['content'];
//            }
//            if($messageBoxData['type']==MessageBox::ACTIVITY_TYPE){
//                $result['msg_url']=$messageBoxData['activity_link'];
//            }
//            $result['msg_type']=$messageBoxData['type'];
//            $result['msg_share_title']=$messageBoxData['title'];
//            $result['msg_share_url']=$messageBoxData['content'];
//            $result['msg_share_description']=$messageBoxData['abstract'];
//
//            $result['msg_status']=0;
//            if($item['click_amount']>0 || $item['forward_amount'] >0) {
//                $result['msg_status']=1;
//            }
//            //var_export($result);die;
//            return $result;
//        });
//        return $list;
//    }
    
    /*
     * 首次通过用户ID获取对应的消息
     *
     */
    public function getMyMsgListFirst($customerID,$paginate=[],$month){
        if(!(int)$customerID){
            return false;
        }
        
        if($month){
            return $this->getMyMsgListMore($customerID,$paginate=[],$month);
        }
        
        
        //默认取当月数据表
        $tableTime=time();
        $lastID=0;
        $rule = [
            'type' => 'month', // 分表方式
            'expr'=>0,
        ];

        $data2=[];
        $data3=[];
    
        $dataObj1=Db::name($this->tableName)
          ->partition(['Ym' => $tableTime], "Ym", $rule)
          ->where(['customer_id' =>$customerID,'jpush_send_status'=>['neq',0]])
          ->order(['id'=>'desc'])
          ->paginate($paginate);
        
        $data1=$dataObj1->all();
        $firstTableAmount1=count($data1);
        
        $lastID=$firstTableAmount1 ? $data1[$firstTableAmount1-1]['id'] :0;

        /*
         * 上一表请求的数据不足一页，从上月表中取出
         */
        if($firstTableAmount1<$paginate['list_rows']){
            $listRows1=$paginate['list_rows']-$firstTableAmount1;
//            $tableTime=strtotime("-1 month");
            $tableTime=getTheMonth(1);
            $dataObj2=Db::name($this->tableName)
                       ->partition(['Ym' => $tableTime], "Ym", $rule)
                       ->where(['customer_id' =>$customerID,'jpush_send_status'=>['neq',0]])
                       ->order(['id'=>'desc'])
                       ->paginate(['list_rows'=>$listRows1,'page'=>1]);
    
            $data2=$dataObj2->all();
            $sencondTableAmount2=count($data2);
            $lastID=$sencondTableAmount2 ? $data2[$sencondTableAmount2-1]['id'] : 0;
            /*
             * 上月表数据不够,从上上月中读取数据
             *
             */
            if($sencondTableAmount2<$listRows1){
                $listRows2=$listRows1-$sencondTableAmount2;
//                $tableTime=strtotime("-2 month");
                $tableTime=getTheMonth(2);
                $dataObj3=Db::name($this->tableName)
                            ->partition(['Ym' => $tableTime], "Ym", $rule)
                            ->where(['customer_id' =>$customerID,'jpush_send_status'=>['neq',0]])
                            ->order(['id'=>'desc'])
                            ->paginate(['list_rows'=>$listRows2,'page'=>1]);
                $data3=$dataObj3->all();
                $thirdTableAmount=count($data3);
                $lastID=$thirdTableAmount ? $data3[$thirdTableAmount-1]['id'] : 0;
            }
            
        }
        
        $data=array_merge($data1,$data2,$data3);
        
        $result=[];
        if(!empty($data)){
            foreach ($data as $k => $v){
                //获取消息内容
                $messageBoxModel=new MessageBox;
                $messageBoxData=$messageBoxModel->getOneMessageBoxDataByID($v['m_b_id']);
                //消息删除不做任何展示
                if($messageBoxData['status']==MessageBox::MESSAGE_STATUS_DELETE){
                    continue;
                }
                $re['msg_id']=$v['m_b_id'];
                $re['activity_id']= 0;
                $re['msg_time_str']=date('Y-m-d H:i',$v['add_time']);
                $re['msg_title']=$messageBoxData['title'];
                $re['msg_description']=$messageBoxData['abstract'];
                $re['msg_img_url']=$messageBoxData['cover_picture_link'];
                //                $result[$k]['msg_url']=$messageBoxData['html'];
    
                if($messageBoxData['type']==MessageBox::ARTICLE_TYPE){
                    $re['msg_url']=$messageBoxData['html'];
                    $re['msg_share_url']=$messageBoxData['html'];
                }
                if($messageBoxData['type']==MessageBox::ACTIVITY_TYPE){
                    $re['msg_url']=$messageBoxData['activity_link'];
                    $re['msg_share_url']=$messageBoxData['activity_link'];
                }
    
    
                $re['msg_type']=$messageBoxData['type'];
                $re['msg_share_title']=$messageBoxData['title'];
                
                $re['msg_share_description']=$messageBoxData['abstract'];
                $re['msg_status']=0;
                if($v['click_amount']>0 || $v['forward_amount'] >0) {
                    $re['msg_status']=1;
                }
                $result[]=$re;
                /*
                $result[$k]['msg_id']=$v['m_b_id'];
                $result[$k]['activity_id']= 0;
                $result[$k]['msg_time_str']=date('Y-m-d H:i',$v['add_time']);
                $result[$k]['msg_title']=$messageBoxData['title'];
                $result[$k]['msg_description']=$messageBoxData['abstract'];
                $result[$k]['msg_img_url']=$messageBoxData['cover_picture_link'];
//                $result[$k]['msg_url']=$messageBoxData['html'];
    
                if($messageBoxData['type']==MessageBox::ARTICLE_TYPE){
                    $result[$k]['msg_url']=$messageBoxData['html'];
                }
                if($messageBoxData['type']==MessageBox::ACTIVITY_TYPE){
                    $result[$k]['msg_url']=$messageBoxData['activity_link'];
                }
                
                
                $result[$k]['msg_type']=$messageBoxData['type'];
                $result[$k]['msg_share_title']=$messageBoxData['title'];
                $result[$k]['msg_share_url']=$messageBoxData['html'];
                $result[$k]['msg_share_description']=$messageBoxData['abstract'];
                $result[$k]['msg_status']=0;
                if($v['click_amount']>0 || $v['forward_amount'] >0) {
                    $result[$k]['msg_status']=1;
                }
                */
            }
        }
        return ['respose'=>['list'=>$result,'table'=>$tableTime.','.$lastID]];
    }
    
    /*
     * 通过用户ID获取对应的消息
     * $month='A,B'  A:哪个表,B:上次取出的id
     */
    public function getMyMsgListMore($customerID,$paginate=[],$month){
    
        return ['respose'=>['list'=>[],'table'=>'']];
        
        if(!(int)$customerID){
            return [];
        }
        list($tableTime,$lastID)=explode(',',$month);
        
        if(!$month || !$tableTime || !$lastID){
            return [];
        }
        
        
        
        //默认取该月数据
        $rule = [
            'type' => 'month', // 分表方式
            'expr'=>0,
        ];
        $finalTableTime=date('Ym',strtotime("-2 month"));
        
        $data2=[];
        $data3=[];
    
        $dataObj1=Db::name($this->tableName)
                    ->partition(['Ym' => $tableTime], "Ym", $rule)
                    ->where(['customer_id' =>$customerID])
                    ->order(['id'=>'desc'])
                    ->paginate($paginate);
    
        $data1=$dataObj1->all();
        $firstTableAmount1=count($data1);
    
        if($firstTableAmount1<$paginate['list_rows']){
            $listRows1=$paginate['list_rows']-$firstTableAmount1;
            $tableTime=date('Ym',strtotime("".date('Ym',$tableTime)." -1 month"));
            if($tableTime>=$finalTableTime){
                $dataObj2=Db::name($this->tableName)
                            ->partition(['Ym' => $tableTime], "Ym", $rule)
                            ->where(['customer_id' =>$customerID])
                            ->order(['id'=>'desc'])
                            ->paginate(['list_rows'=>$listRows1,'page'=>1]);
                $data2=$dataObj2->all();
                $sencondTableAmount2=count($data2);
            }
    
        }
    
    
        /*
             * 上月表数据不够,从上上月中读取数据
             *
             */
        if($sencondTableAmount2<$listRows1){
            $listRows2=$listRows1-$sencondTableAmount2;
            $tableTime=date('Ym',strtotime("".date('Ym',$tableTime)." -2 month"));
            $dataObj3=Db::name($this->tableName)
                        ->partition(['Ym' => $tableTime], "Ym", $rule)
                        ->where(['customer_id' =>$customerID])
                        ->order(['id'=>'desc'])
                        ->paginate(['list_rows'=>$listRows2,'page'=>1]);
            $data3=$dataObj3->all();
        }
        
        $data=array_merge($data1,$data2,$data3);
    
        $result=[];
        if(!empty($data)){
            foreach ($data as $k => $v){
                $result[$k]['msg_id']=$v['m_b_id'];
                $result[$k]['activity_id']= 0;
                $result[$k]['msg_time_str']=date('Y-m-d H:i',$v['add_time']);
            
            
                //获取消息内容
                $messageBoxModel=new MessageBox;
                $messageBoxData=$messageBoxModel->getOneMessageBoxDataByID($v['m_b_id']);
            
                $result[$k]['msg_title']=$messageBoxData['title'];
                $result[$k]['msg_description']=$messageBoxData['abstract'];
                $result[$k]['msg_img_url']=$messageBoxData['cover_picture_link'];
                $result[$k]['msg_url']=$messageBoxData['content'];
                $result[$k]['msg_type']=$messageBoxData['type'];
                $result[$k]['msg_share_title']=$messageBoxData['title'];
                $result[$k]['msg_share_url']=$messageBoxData['content'];
                $result[$k]['msg_share_description']=$messageBoxData['abstract'];
            
                $result[$k]['msg_status']=0;
                if($v['click_amount']>0 || $v['forward_amount'] >0) {
                    $result[$k]['msg_status']=1;
                }
            }
        }
        return $result;
    }
    /*
     *插入数据
     */
    public function InsertMessageTargetUserData($insertData){
        $insertDate=time();
        $rule = [
            'type' => 'month', // 分表方式
            'expr'=>0,
        ];
        Db::name($this->tableName)
          ->partition(['Ym' => $insertDate], "Ym", $rule)
          ->insert($insertData);
        
    }
    
    /*
     * 获取Boss指定的消息用户
     */
    public function getMessageTargetUserByBoss($msgId) {
        return Db::name($this->tableName)->where(['m_b_id'=>$msgId])->delete();
    }
    
    
    /*
     * 添加转发次数
     */
    public function addForwardAmount($data){
        $msgId=$data['m_b_id'];
        $msgData=Db::name('message_box')->field(['add_time'])->where(['id'=>$msgId])->find();
        if(!$msgData){
            return false;
        }
    
        $rule = [
            'type' => 'month', // 分表方式
            'expr'=>0,
        ];
        Db::name($this->tableName)
          ->partition(['Ym' => $msgData['add_time']], "Ym", $rule)
          ->where(['m_b_id'=>$msgId,'customer_id'=>$data['customer_id']])
          ->setInc('forward_amount');
        
        $data=Db::name($this->tableName)
                ->partition(['Ym' => $msgData['add_time']], "Ym", $rule)
                ->field('forward_amount')
                ->where(['m_b_id'=>$msgId,'customer_id'=>$data['customer_id']])
                ->find();
    
        if($data['forward_amount']==1){
            //转发次数加1
            $messageBoxModel=new MessageBox;
            $messageBoxModel->setForwardAmountIncByID($msgId);
        }

    }
    
    /*
     * 添加阅读量
     */
    public function addClickAmount($data){
        $msgId=$data['m_b_id'];
        $msgData=Db::name('message_box')->field(['add_time'])->where(['id'=>$msgId])->find();
        if(!$msgData){
            return false;
        }
        
        $rule = [
            'type' => 'month', // 分表方式
            'expr'=>0,
        ];
        Db::name($this->tableName)
          ->partition(['Ym' => $msgData['add_time']], "Ym", $rule)
          ->where(['m_b_id'=>$msgId,'customer_id'=>$data['customer_id']])
          ->setInc('click_amount');
        
        $data=Db::name($this->tableName)
                ->partition(['Ym' => $msgData['add_time']], "Ym", $rule)
                ->field('click_amount')
                ->where(['m_b_id'=>$msgId,'customer_id'=>$data['customer_id']])
                ->find();
        
        if($data['click_amount']==1){
            //消息点击量加1
            $messageBoxModel=new MessageBox;
            $messageBoxData=$messageBoxModel->setClickAmountIncByID($msgId);
        }
        
    }
    
    /*
     * 获取我的未读消息数
     */
    public function getMyNoticeAmount($customerID){
        if(!(int)$customerID)return false;
        $rule = [
            'type' => 'month', // 分表方式
            'expr'=>0,
        ];
        $count=0;
        //当月消息未读数
        $data=Db::name($this->tableName)
          ->partition(['Ym' =>time()], "Ym", $rule)
          ->field('id,m_b_id')
          ->where(['customer_id'=>$customerID,'click_amount'=>['eq',0],'forward_amount'=>['eq',0] ,'jpush_send_status'=>['neq',0]])
          ->select();
        if($count=count($data)){
            foreach ($data as $v){
                //消息息是否删除或者
                $messageBox=new MessageBox;
                //getStatusByID
                $status=$messageBox->getStatusByID($v['m_b_id']);
                if($status!=2){
                    $count-=1;
                }
            }
            if($count){
                return $count;
            }
        }
        
        //上月消息未读数
        $data=Db::name($this->tableName)
            ->partition(['Ym' =>strtotime("".date('Ym')." -1 month")], "Ym", $rule)
            ->field('id')
            ->where(['customer_id'=>$customerID,'click_amount'=>['eq',0],'forward_amount'=>['eq',0],'jpush_send_status'=>['neq',0]])
            ->select();
        if($count=count($data)){
            foreach ($data as $v){
                //消息息是否删除或者
                $messageBox=new MessageBox;
                //getStatusByID
                $status=$messageBox->getStatusByID($v['m_b_id']);
                if($status!=2){
                    $count-=1;
                }
            }
            if($count){
                return $count;
            }
        }
        
        //上上月消息未读数
        $data=Db::name($this->tableName)
          ->partition(['Ym' =>strtotime("".date('Ym')." -2 month")], "Ym", $rule)
            ->field('id')
            ->where(['customer_id'=>$customerID,'click_amount'=>['eq',0],'forward_amount'=>['eq',0],'jpush_send_status'=>['neq',0]])
            ->select();
        if($count=count($data)){
            foreach ($data as $v){
                //消息息是否删除或者
                $messageBox=new MessageBox;
                //getStatusByID
                $status=$messageBox->getStatusByID($v['m_b_id']);
                if($status!=2){
                    $count-=1;
                }
            }
            if($count){
                return $count;
            }
        }
        
        return $count;
    }
}